package com.yonyou.brigade.third_parties.ystrip.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.props.PropUtil;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.ystrip.model.YStripUser;
import com.yonyou.brigade.third_parties.ystrip.model.YstripUserHistory;
import com.yonyou.brigade.third_parties.ystrip.service.IYStripPublicService;
import com.yonyou.brigade.third_parties.ystrip.service.IYStripUserService;
import com.yonyou.brigade.third_parties.ystrip.service.IYstripUserHistoryService;
import com.yonyou.ybzboot.starter.common.exception.BaseException;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class YStripUserServiceImpl implements IYStripUserService {

    @Autowired
    @Qualifier("ystripUserHistoryServiceImpl")
    IYstripUserHistoryService iYstripUserHistoryService;

    @Qualifier("YStripPublicServiceImpl")
    @Autowired
    IYStripPublicService iyStripPublicService;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    IBriChannelService iBriChannelService;

    @Autowired
    private PropUtil propUtil;


    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Override
    public void syncAllUserToYStrip(String tenant,String orgpk) {
        Map<String,String> params = new HashMap<>();
        params.put("tenant",tenant);
        params.put("orgpk",orgpk);


        BriChannel briChannel = iBriChannelService.getEnableInfoByTenantOrg(tenant,orgpk,"ystrip");
        if (briChannel == null){
            throw new BaseException(-100,"该组织未开通云上火车票");
        }

        JSONObject configJSON = JSON.parseObject(briChannel.getConfig());

        List<YStripUser> yStripUsers = iYstripUserHistoryService.selectNoSyncUser(params);
        if (yStripUsers == null || yStripUsers.size() == 0){
            return;
        }
        yStripUsers.forEach(yStripUser -> {
            yStripUser.setCompanyNo(configJSON.getString("companyNo"));
        });
        iyStripPublicService.insertUser(yStripUsers);



    }

    /**
     * 获取登录url
     *
     * @param tenant
     * @param org
     * @param phone
     * @param pageType
     * @param pcOrH5
     * @param jsonExt
     * @return
     */
    @Override
    public String loginUrl(String tenant, String org, String phone, String pageType, String pcOrH5, String jsonExt) {
        String resultUrl= "";
        BriChannel briChannel = iBriChannelService.getEnableInfoByTenantOrg(tenant,org,"ystrip");
        if(briChannel==null) {
            resultUrl = propUtil.getNO_ACCESS_URL();
            return resultUrl;
        }else {
            Wrapper<YstripUserHistory> wrapper = new EntityWrapper<>();
            JSONObject configJSON = JSON.parseObject(briChannel.getConfig());
            wrapper.eq(YstripUserHistory.COMPANY_NO,configJSON.getString("companyNo"));
            wrapper.eq(YstripUserHistory.USER_PHONE,phone);
            List<YstripUserHistory> ystripUserHistories = iYstripUserHistoryService.selectList(wrapper);
            if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                if (ystripUserHistories == null || ystripUserHistories.size() == 0){
                    //如果当前用户没有同步给云上火车票，则进行同步
                    syncSingleUserToYStrip(tenant,org,phone);
                }
            }
            ystripUserHistories = iYstripUserHistoryService.selectList(wrapper);
            if (ystripUserHistories == null || ystripUserHistories.size() == 0){
                resultUrl= propUtil.getNO_ACCESS_URL();
                return resultUrl;
            }

            YstripUserHistory ystripUserHistory = ystripUserHistories.get(0);
            String jumpType = "";
            if ("pc".equals(pcOrH5.toLowerCase())){
                jumpType = "SYS";
            }else {
                jumpType = "TH5";
            }
            resultUrl = iyStripPublicService.ssoLogin(jumpType,convertYStripUser(ystripUserHistory));
        }

        return resultUrl;
    }

    @Override
    public void syncSingleUserToYStrip(String tenant, String orgpk, String phone) {

        BriChannel briChannel = iBriChannelService.getEnableInfoByTenantOrg(tenant,orgpk,"ystrip");
        if (briChannel == null){
            throw new BaseException(-100,"当前组织未开通云上火车票");
        }

        UcUserDto ucUserDTO= iUserCenterService.getCompleteUcUserDtoByPhone(phone,tenant);

        YStripUser yStripUser = new YStripUser();
        JSONObject configJSON = JSON.parseObject(briChannel.getConfig());
        yStripUser.setCompanyNo(configJSON.getString("companyNo"));
        yStripUser.setUserNo(ucUserDTO.getPersonCode());
        yStripUser.setUserName(ucUserDTO.getUserName());
        yStripUser.setUserPhone(ucUserDTO.getPhone());
        yStripUser.setUserEmail(ucUserDTO.getEmail());
        yStripUser.setUserId(ucUserDTO.getUserId());
        yStripUser.setCardNo(ucUserDTO.getPassengerId());
        yStripUser.setRemark(configJSON.getString("companyName"));
        iyStripPublicService.insertUser(Collections.singletonList(yStripUser));
    }

    private YStripUser convertYStripUser(YstripUserHistory ystripUserHistory){
        String jsonStr = JSON.toJSONString(ystripUserHistory);
        YStripUser yStripUser = JSON.parseObject(jsonStr,YStripUser.class);
        return yStripUser;
    }
}
